const api = require('../../utils/api');
const util = require('../../utils/util');

Page({
  data: {
    // 日期和餐食类型
    date: '',
    time: '',
    mealType: '早餐', // 默认为早餐
    mealTypeOptions: ['早餐', '午餐', '晚餐', '加餐'],
    mealTypes: ['早餐', '午餐', '晚餐', '加餐'], // 修复：添加与wxml中对应的mealTypes属性
    mealTypeIndex: 0, // 添加索引属性
    
    // 食物搜索弹窗
    showFoodSearch: false, // 添加控制弹窗显示的属性
    
    // 搜索相关
    searchValue: '',
    searchKeyword: '', // 添加searchKeyword属性
    searching: false,
    searchResults: [],
    
    // 当前已选择的食物
    selectedFoods: [],
    foods: [], // 添加foods属性，与wxml保持一致
    
    // 食物分类
    categories: [],
    currentCategory: '全部',
    
    // 推荐食物列表
    recommendedFoods: [],
    loading: false,
    
    // 自定义食物表单
    showCustomFoodForm: false,
    customFoodCategoryIndex: 0,
    customFoodUnitIndex: 1, // 默认为"克"
    customFood: {
      name: '',
      category: '其他',
      calories: '',
      carbs: '',
      protein: '',
      fat: '',
      quantity: '100',
      unit: '克'
    },
    
    // 营养总计
    totalCalories: 0,
    totalCarbs: 0,
    totalProtein: 0,
    totalFat: 0,
    
    // 食物详情和份量选择相关
    showFoodDetail: false,
    currentFood: null,
    selectedQuantity: 1,
    selectedUnitIndex: 0,
    unitOptions: ['份', '克', '个', '杯', '勺'],
    selectedPortion: -1, // 选中的常用份量索引
    adjustedNutrition: {}, // 根据当前选择的份量计算的营养值
  },
  
  onLoad(options) {
    // 尝试从查询参数获取日期
    let date = options.date || '';
    
    // 如果没有传递日期，使用当前日期
    if (!date) {
      const today = new Date();
      const year = today.getFullYear();
      const month = (today.getMonth() + 1).toString().padStart(2, '0');
      const day = today.getDate().toString().padStart(2, '0');
      date = `${year}-${month}-${day}`;
    }
    
    // 获取当前时间
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const time = `${hours}:${minutes}`;
    
    // 根据当前时间确定默认餐食类型
    let mealTypeIndex = 0;
    const hourNum = now.getHours();
    if (hourNum >= 5 && hourNum < 10) {
      mealTypeIndex = 0; // 早餐
    } else if (hourNum >= 10 && hourNum < 14) {
      mealTypeIndex = 1; // 午餐
    } else if (hourNum >= 17 && hourNum < 21) {
      mealTypeIndex = 2; // 晚餐
    } else {
      mealTypeIndex = 3; // 加餐
    }
    
    this.setData({
      date,
      time,
      mealTypeIndex,
      mealType: this.data.mealTypeOptions[mealTypeIndex],
      mealDate: date,
      mealTime: time
    });
    
    // 加载食物分类
    this.loadFoodCategories();
    
    // 加载推荐食物
    this.loadRecommendedFoods();
  },
  
  // 加载食物分类
  async loadFoodCategories() {
    try {
      const result = await api.diet.getFoodCategories();
      if (result && result.success) {
        // 添加"全部"分类
        const categories = ['全部', ...result.data];
        
        this.setData({
          categories
        });
      }
    } catch (error) {
      console.error('加载食物分类失败:', error);
      wx.showToast({
        title: '获取食物分类失败',
        icon: 'none'
      });
    }
  },
  
  // 加载推荐食物
  async loadRecommendedFoods() {
    this.setData({ loading: true });
    
    try {
      const result = await api.diet.getRecommendedFoods(
        this.data.mealType,
        this.data.currentCategory !== '全部' ? this.data.currentCategory : null
      );
      
      if (result && result.success) {
        this.setData({
          recommendedFoods: result.data,
          loading: false
        });
      } else {
        this.setData({
          recommendedFoods: [],
          loading: false
        });
      }
    } catch (error) {
      console.error('加载推荐食物失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载推荐食物失败',
        icon: 'none'
      });
    }
  },
  
  // 搜索食物
  async searchFood() {
    const query = this.data.searchKeyword.trim();
    if (!query) return;
    
    this.setData({ searching: true });
    
    try {
      // 优先使用天行API搜索
      const result = await api.diet.searchTianapiFood(
        query,
        0,  // 按名称搜索
        15  // 返回15条结果
      );
      
      if (result && result.success && result.data && result.data.length > 0) {
        this.setData({
          searchResults: result.data,
          searching: false
        });
      } else {
        // 如果天行API没有结果，尝试本地数据库搜索
        const localResult = await api.diet.searchFoods(
          query,
          this.data.currentCategory !== '全部' ? this.data.currentCategory : null
        );
        
        if (localResult && localResult.success) {
          this.setData({
            searchResults: localResult.data,
            searching: false
          });
        } else {
          this.setData({
            searchResults: [],
            searching: false
          });
          
          wx.showToast({
            title: '未找到匹配的食物',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('搜索食物失败:', error);
      this.setData({ searching: false });
      wx.showToast({
        title: '搜索失败',
        icon: 'none'
      });
    }
  },
  
  // 处理搜索输入变化
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    
    // 如果输入框为空，清空搜索结果
    if (!e.detail.value.trim()) {
      this.setData({
        searchResults: []
      });
    } else {
      // 当输入内容变化时自动搜索
      this.searchFood();
    }
  },
  
  // 显示食物搜索弹窗
  showFoodSearch() {
    this.setData({
      showFoodSearch: true,
      searchKeyword: '',
      searchResults: []
    });
  },
  
  // 隐藏食物搜索弹窗
  hideFoodSearch() {
    this.setData({
      showFoodSearch: false
    });
  },
  
  // 显示食物详情和份量选择弹窗
  showFoodDetail(e) {
    const food = e.currentTarget.dataset.food;
    if (!food) return;
    
    // 设置默认单位
    let unitIndex = 0; // 默认为"份"
    
    // 重置份量选择状态
    this.setData({
      showFoodDetail: true,
      currentFood: food,
      selectedQuantity: 1,
      selectedUnitIndex: unitIndex,
      selectedPortion: -1
    });
    
    // 计算调整后的营养信息
    this.calculateAdjustedNutrition();
  },
  
  // 隐藏食物详情弹窗
  hideFoodDetail() {
    this.setData({
      showFoodDetail: false,
      currentFood: null,
      adjustedNutrition: {}
    });
  },
  
  // 增加选择的食物份量
  increaseSelectedQuantity() {
    const quantity = this.data.selectedQuantity + 1;
    this.setData({ selectedQuantity: quantity });
    this.calculateAdjustedNutrition();
  },
  
  // 减少选择的食物份量
  decreaseSelectedQuantity() {
    if (this.data.selectedQuantity > 1) {
      const quantity = this.data.selectedQuantity - 1;
      this.setData({ selectedQuantity: quantity });
      this.calculateAdjustedNutrition();
    }
  },
  
  // 处理手动输入的份量
  onSelectedQuantityInput(e) {
    const value = e.detail.value;
    const quantity = parseFloat(value) || 1;
    if (quantity > 0) {
      this.setData({ selectedQuantity: quantity });
      this.calculateAdjustedNutrition();
    }
  },
  
  // 处理单位选择变更
  onSelectedUnitChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({ 
      selectedUnitIndex: index,
      selectedPortion: -1 // 重置常用份量选择
    });
    this.calculateAdjustedNutrition();
  },
  
  // 选择常用份量
  selectCommonPortion(e) {
    const index = e.currentTarget.dataset.index;
    const weight = e.currentTarget.dataset.weight;
    
    // 如果选择克为单位，直接设置克数
    const unitIndex = this.data.unitOptions.indexOf('克');
    
    this.setData({
      selectedPortion: index,
      selectedQuantity: weight,
      selectedUnitIndex: unitIndex
    });
    
    this.calculateAdjustedNutrition();
  },
  
  // 计算根据选择份量调整后的营养值
  calculateAdjustedNutrition() {
    const food = this.data.currentFood;
    if (!food) return;
    
    const quantity = this.data.selectedQuantity;
    const unit = this.data.unitOptions[this.data.selectedUnitIndex];
    const baseAmount = food.baseAmount || 100; // 默认基准量为100克
    
    let ratio = 1; // 默认比例
    
    // 根据单位类型计算比例
    if (unit === '克') {
      ratio = quantity / baseAmount;
    } else if (unit === '份') {
      // 一份默认为基准量
      ratio = quantity;
    } else if (unit === '个' || unit === '杯' || unit === '勺') {
      // 对于其他单位，需要根据食物类型和单位精确估算比例
      if (food.category === '水果类' && unit === '个') {
        // 修正：使用更精确的重量估算，一个苹果约为150克
        // 计算相对于基准量的比例，而不是简单乘以固定倍数
        ratio = quantity * (150 / baseAmount);
      } else if (food.category === '蔬菜类' && unit === '杯') {
        // 修正：一杯蔬菜约200克
        ratio = quantity * (200 / baseAmount);
      } else if (unit === '勺') {
        // 修正：一勺约10克
        ratio = quantity * (10 / baseAmount);
      } else {
        // 默认情况使用食物的通用份量（如果存在）
        if (food.commonPortions && food.commonPortions.length > 0 && food.commonPortions[0].gramWeight) {
          ratio = quantity * (food.commonPortions[0].gramWeight / baseAmount);
        } else {
          // 没有通用份量信息时，使用保守估计
          ratio = quantity;
        }
      }
    }
    
    console.log(`食物: ${food.name}, 单位: ${unit}, 数量: ${quantity}, 基准量: ${baseAmount}克, 换算比例: ${ratio}`);
    
    // 计算调整后的营养值
    const adjustedCalories = food.calories * ratio;
    const adjustedCarbs = food.carbs * ratio;
    const adjustedProtein = food.protein * ratio;
    const adjustedFat = food.fat * ratio;
    
    this.setData({
      adjustedNutrition: {
        calories: Math.round(adjustedCalories),
        carbs: Math.round(adjustedCarbs * 10) / 10,
        protein: Math.round(adjustedProtein * 10) / 10,
        fat: Math.round(adjustedFat * 10) / 10
      }
    });
  },
  
  // 确认添加食物
  confirmAddFood() {
    const food = this.data.currentFood;
    if (!food) return;
    
    const quantity = this.data.selectedQuantity;
    const unitIndex = this.data.selectedUnitIndex;
    const unit = this.data.unitOptions[unitIndex];
    const baseAmount = food.baseAmount || 100; // 默认基准量为100克
    
    // 计算正确的营养值比例
    let ratio = 1;
    
    // 根据单位类型计算比例 - 与calculateAdjustedNutrition保持一致
    if (unit === '克') {
      ratio = quantity / baseAmount;
    } else if (unit === '份') {
      ratio = quantity;
    } else if (unit === '个' || unit === '杯' || unit === '勺') {
      if (food.category === '水果类' && unit === '个') {
        ratio = quantity * (150 / baseAmount);
      } else if (food.category === '蔬菜类' && unit === '杯') {
        ratio = quantity * (200 / baseAmount);
      } else if (unit === '勺') {
        ratio = quantity * (10 / baseAmount);
      } else if (food.commonPortions && food.commonPortions.length > 0 && food.commonPortions[0].gramWeight) {
        ratio = quantity * (food.commonPortions[0].gramWeight / baseAmount);
      } else {
        ratio = quantity;
      }
    }
    
    // 获取计算好的营养值，如果存在，否则重新计算
    let adjustedNutrition = this.data.adjustedNutrition;
    if (!adjustedNutrition) {
      const adjustedCalories = food.calories * ratio;
      const adjustedCarbs = food.carbs * ratio;
      const adjustedProtein = food.protein * ratio;
      const adjustedFat = food.fat * ratio;
      
      adjustedNutrition = {
        calories: Math.round(adjustedCalories),
        carbs: Math.round(adjustedCarbs * 10) / 10,
        protein: Math.round(adjustedProtein * 10) / 10,
        fat: Math.round(adjustedFat * 10) / 10
      };
    }
    
    // 创建一个新的食物对象，包含选择的份量信息和原始营养数据（不包含计算后的值）
    const newFood = {
      ...food,
      id: food._id || food.id || Date.now(),
      quantity: quantity,
      unit: unit,
      // 确保必要字段存在
      name: food.name || '未命名食物',
      calories: food.calories || 0,
      carbs: food.carbs || 0,
      protein: food.protein || 0,
      fat: food.fat || 0,
      fiber: food.fiber || 0,
      category: food.category || '其他',
      baseAmount: food.baseAmount || 100,
      baseUnit: food.baseUnit || '克'
      // 不将调整后的营养值直接存入，因为updateNutritionTotals会负责计算
    };
    
    const foods = [...this.data.foods, newFood];
    
    this.setData({
      foods,
      showFoodDetail: false,
      showFoodSearch: false,  // 同时关闭搜索弹窗
      currentFood: null
    });
    
    // 更新营养总计
    this.updateNutritionTotals();
    
    // 如果食物来源是天行API且没有_id，则保存到本地数据库
    if (food.source === 'tianapi' && !food._id) {
      this.saveFoodToDatabase(newFood);
    }
  },
  
  // 保存食物到数据库
  async saveFoodToDatabase(food) {
    try {
      // 准备完整的食物数据对象用于保存
      const foodDataToSave = {
        name: food.name,
        calories: food.calories,
        carbs: food.carbs || 0,
        protein: food.protein || 0,
        fat: food.fat || 0,
        fiber: food.fiber || 0,
        sugar: food.sugar || 0,
        category: food.category || '其他',
        source: 'tianapi',
        commonPortions: food.commonPortions || [{ description: '一份', gramWeight: 100 }],
        baseAmount: food.baseAmount || 100,
        baseUnit: food.baseUnit || '克'
      };
      
      // 保存食物到本地数据库
      const saveResult = await api.diet.saveTianapiFood(foodDataToSave);
      console.log('食物已保存到本地数据库:', saveResult);
      
      // 如果保存成功，更新食物ID
      if (saveResult && saveResult.success && saveResult.data) {
        // 查找并更新当前食物的ID
        const index = this.data.foods.findIndex(item => item.id === food.id);
        if (index !== -1) {
          const updatedFoods = [...this.data.foods];
          updatedFoods[index]._id = saveResult.data._id;
          updatedFoods[index].id = saveResult.data._id;
          
          this.setData({
            foods: updatedFoods
          });
        }
      }
    } catch (error) {
      console.error('保存食物到本地数据库失败:', error);
      // 继续使用，不影响用户添加食物
    }
  },
  
  // 编辑已添加食物的份量
  editFoodQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const food = this.data.foods[index];
    
    // 打开一个弹窗让用户编辑份量
    wx.showModal({
      title: '编辑份量',
      content: `当前: ${food.quantity}${food.unit}`,
      editable: true,
      placeholderText: '请输入新的份量',
      success: (res) => {
        if (res.confirm) {
          const newQuantity = parseFloat(res.content);
          if (!isNaN(newQuantity) && newQuantity > 0) {
            // 更新食物份量
            const foods = [...this.data.foods];
            foods[index].quantity = newQuantity;
            
            this.setData({ foods });
            this.updateNutritionTotals();
          }
        }
      }
    });
  },
  
  // 添加食物到列表 - 不再直接使用此方法，而是通过食物详情弹窗确认后添加
  async addFood(e) {
    // 这个方法保留以保持向后兼容性，但正常流程不会调用它
    const food = e.currentTarget.dataset.food;
    this.showFoodDetail(e);
  },
  
  // 增加食物数量
  increaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const foods = [...this.data.foods];
    const index = foods.findIndex(item => item.id === id);
    
    if (index !== -1) {
      foods[index].quantity += 1;
      this.setData({ foods });
      this.updateNutritionTotals();
    }
  },
  
  // 减少食物数量
  decreaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const foods = [...this.data.foods];
    const index = foods.findIndex(item => item.id === id);
    
    if (index !== -1 && foods[index].quantity > 1) {
      foods[index].quantity -= 1;
      this.setData({ foods });
      this.updateNutritionTotals();
    }
  },
  
  // 删除食物
  deleteFood(e) {
    const id = e.currentTarget.dataset.id;
    const foods = this.data.foods.filter(item => item.id !== id);
    this.setData({ foods });
    this.updateNutritionTotals();
  },
  
  // 更新营养总计
  updateNutritionTotals() {
    const foods = this.data.foods;
    let totalCalories = 0, totalCarbs = 0, totalProtein = 0, totalFat = 0;
    
    // 格式化foods数组中的营养值，考虑单位和份量
    const formattedFoods = foods.map(food => {
      // 深拷贝避免直接修改原始数据
      const formattedFood = { ...food };
      
      // 基准量和单位
      const baseAmount = food.baseAmount || 100;
      const unit = food.unit;
      const quantity = parseFloat(food.quantity) || 1;
      
      // 计算比例
      let ratio = 1;
      if (unit === '克') {
        ratio = quantity / baseAmount;
      } else if (unit === '份') {
        ratio = quantity;
      } else if (unit === '个' || unit === '杯' || unit === '勺') {
        if (food.category === '水果类' && unit === '个') {
          ratio = quantity * (150 / baseAmount);
        } else if (food.category === '蔬菜类' && unit === '杯') {
          ratio = quantity * (200 / baseAmount);
        } else if (unit === '勺') {
          ratio = quantity * (10 / baseAmount);
        } else if (food.commonPortions && food.commonPortions.length > 0 && food.commonPortions[0].gramWeight) {
          ratio = quantity * (food.commonPortions[0].gramWeight / baseAmount);
        } else {
          ratio = quantity;
        }
      }
      
      // 预计算并格式化营养值
      formattedFood.displayCalories = Math.round(food.calories * ratio);
      formattedFood.displayCarbs = Math.round(food.carbs * ratio * 10) / 10;
      formattedFood.displayProtein = Math.round(food.protein * ratio * 10) / 10;
      formattedFood.displayFat = Math.round(food.fat * ratio * 10) / 10;
      
      // 累加到总计
      totalCalories += formattedFood.displayCalories;
      totalCarbs += formattedFood.displayCarbs;
      totalProtein += formattedFood.displayProtein;
      totalFat += formattedFood.displayFat;
      
      return formattedFood;
    });
    
    this.setData({
      foods: formattedFoods,
      totalCalories: Math.round(totalCalories),
      totalCarbs: Math.round(totalCarbs * 10) / 10,
      totalProtein: Math.round(totalProtein * 10) / 10,
      totalFat: Math.round(totalFat * 10) / 10
    });
  },
  
  // 处理日期变更
  onDateChange(e) {
    this.setData({
      date: e.detail.value,
      mealDate: e.detail.value
    });
  },
  
  // 处理时间变更
  onTimeChange(e) {
    this.setData({
      time: e.detail.value,
      mealTime: e.detail.value
    });
  },
  
  // 处理餐食类型变更
  onMealTypeChange(e) {
    const index = parseInt(e.detail.value);
    const mealType = this.data.mealTypeOptions[index];
    
    this.setData({
      mealTypeIndex: index,
      mealType
    });
    
    // 重新加载推荐食物
    this.loadRecommendedFoods();
  },
  
  // 保存餐食记录
  async saveMeal() {
    const { date, time, mealType, foods } = this.data;
    
    // 验证必填字段
    if (!date || !time || !mealType) {
      wx.showToast({
        title: '请完成所有必填项',
        icon: 'none'
      });
      return;
    }
    
    // 验证是否选择了食物
    if (foods.length === 0) {
      wx.showToast({
        title: '请至少添加一种食物',
        icon: 'none'
      });
      return;
    }
    
    // 准备餐食数据
    const mealData = {
      date,
      time,
      mealType,
      foods: foods.map(food => {
        // 为自定义食物保留完整信息，对已有foodId的食物只保留引用
        const baseFood = {
          name: food.name,
          quantity: parseFloat(food.quantity) || 1,
          unit: food.unit || '份',
          calories: food.displayCalories || food.calories, // 使用计算后的卡路里值
          carbs: food.displayCarbs || food.carbs, // 使用计算后的碳水值
          protein: food.displayProtein || food.protein, // 使用计算后的蛋白质值
          fat: food.displayFat || food.fat // 使用计算后的脂肪值
        };
        
        // 如果是自定义食物，添加完整信息
        if (food.isCustom) {
          return {
            ...baseFood,
            isCustom: true,
            category: food.category || '其他',
            baseAmount: food.baseAmount || 100,
            baseUnit: food.baseUnit || '克'
          };
        } else {
          // 非自定义食物，使用foodId引用
          return {
            ...baseFood,
            foodId: food._id || food.id
          };
        }
      })
    };
    
    try {
      wx.showLoading({ title: '保存中...' });
      const result = await api.diet.addMeal(mealData);
      
      if (result && result.success) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 延迟返回上一页，以便用户看到成功提示
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存餐食记录失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },
  
  // 取消添加，返回上一页
  onCancel() {
    wx.navigateBack();
  },
  
  // 保存餐食按钮点击
  onSave() {
    this.saveMeal();
  },
  
  // 显示自定义食物表单
  showCustomFoodForm() {
    // 将搜索关键词作为参数传递到新页面
    wx.navigateTo({
      url: '/pages/customFoodAdd/customFoodAdd?keyword=' + encodeURIComponent(this.data.searchKeyword || '')
    });
  },
  
  // 隐藏自定义食物表单
  hideCustomFoodForm() {
    this.setData({
      showCustomFoodForm: false
    });
  },
  
  // 处理自定义食物名称输入
  onCustomFoodNameInput(e) {
    this.setData({
      'customFood.name': e.detail.value
    });
  },
  
  // 处理自定义食物分类选择
  onCustomFoodCategoryChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      customFoodCategoryIndex: index,
      'customFood.category': this.data.categories[index]
    });
  },
  
  // 处理自定义食物热量输入
  onCustomFoodCaloriesInput(e) {
    const value = e.detail.value;
    // 确保输入的是有效数字
    if (!isNaN(parseFloat(value))) {
      this.setData({
        'customFood.calories': value
      });
    }
  },
  
  // 处理自定义食物碳水输入
  onCustomFoodCarbsInput(e) {
    const value = e.detail.value;
    if (!isNaN(parseFloat(value))) {
      this.setData({
        'customFood.carbs': value
      });
    }
  },
  
  // 处理自定义食物蛋白质输入
  onCustomFoodProteinInput(e) {
    const value = e.detail.value;
    if (!isNaN(parseFloat(value))) {
      this.setData({
        'customFood.protein': value
      });
    }
  },
  
  // 处理自定义食物脂肪输入
  onCustomFoodFatInput(e) {
    const value = e.detail.value;
    if (!isNaN(parseFloat(value))) {
      this.setData({
        'customFood.fat': value
      });
    }
  },
  
  // 处理自定义食物基准量输入
  onCustomFoodQuantityInput(e) {
    const value = e.detail.value;
    if (!isNaN(parseFloat(value)) && parseFloat(value) > 0) {
      this.setData({
        'customFood.quantity': value
      });
    }
  },
  
  // 处理自定义食物单位选择
  onCustomFoodUnitChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      customFoodUnitIndex: index,
      'customFood.unit': this.data.unitOptions[index]
    });
  },
  
  // 确认添加自定义食物
  confirmAddCustomFood() {
    const { customFood } = this.data;
    
    // 验证必填字段
    if (!customFood.name) {
      wx.showToast({
        title: '请输入食物名称',
        icon: 'none'
      });
      return;
    }
    
    // 验证营养数据
    if (!customFood.calories || isNaN(parseFloat(customFood.calories))) {
      wx.showToast({
        title: '请输入有效的热量值',
        icon: 'none'
      });
      return;
    }
    
    // 准备食物数据
    const newFood = {
      id: `custom_${Date.now()}`, // 生成临时ID
      name: customFood.name,
      category: customFood.category || '其他',
      calories: parseFloat(customFood.calories) || 0,
      carbs: parseFloat(customFood.carbs) || 0,
      protein: parseFloat(customFood.protein) || 0,
      fat: parseFloat(customFood.fat) || 0,
      quantity: 1, // 默认添加一份
      unit: customFood.unit || '份',
      baseAmount: parseFloat(customFood.quantity) || 100,
      baseUnit: customFood.unit || '克',
      isCustom: true // 标记为自定义食物
    };
    
    // 添加到食物列表
    const foods = [...this.data.foods, newFood];
    
    this.setData({
      foods,
      showCustomFoodForm: false,
      showFoodSearch: false
    });
    
    // 更新营养总计
    this.updateNutritionTotals();
    
    // 提示用户
    wx.showToast({
      title: '已添加到餐食',
      icon: 'success',
      duration: 1500
    });
  },
}); 